import json
import requests
import base_request
from bs4 import BeautifulSoup
rates = []
names = []
pics = []
uris = []
countires = []
directors = []
actors = []
types = []
years = []
times = []
intros = []
#获取简介
def get_movie_intro(uri,downMovie,name,rate):
    resp = requests.get(uri,headers=base_request.headers)
    bs = BeautifulSoup(resp.text,'lxml')
    mins = bs.select_one('#info span[property="v:runtime"]').text
    tintros = bs.select_one('#link-report-intra span[property="v:summary"]').text.strip()
    if downMovie:
        n = bs.select_one('a.related-pic-video')
        if n:
            m_uri = n.get('href')
            resp2 = requests.get(m_uri, headers=base_request.headers)
            bs = BeautifulSoup(resp2.text, 'lxml')
            vi = bs.select_one('video source')
            print(vi.get('src'))
            resp3 = requests.get(vi.get('src'))
            try:
                filname = f'movie/{name}_{rate}.mp4'
                with open(filname.replace('*',''), 'wb') as f:
                    f.write(resp3.content)
            except Exception as e:
                print(f">>>{e}")
    return mins,tintros

#处理基本数据
def handle_base_data(dic):
    movies = dic['items']
    for m in movies:
        rates.append(m['rating']['value'])
        names.append(m['title'])
        pics.append(m['pic']['normal'])
        uri = f'https://movie.douban.com/subject/{m["id"]}/'
        uris.append(uri)
        info = m['card_subtitle']
        infos = info.split("/")
        # print(infos)
        years.append(infos[0].strip())
        countires.append(infos[1].strip().replace(' ','|'))
        types.append(infos[2].strip().replace(' ','|'))
        directors.append(infos[3].strip().replace(' ','|'))
        actors.append(infos[4].strip().replace(' ','|'))
        print("------------"+m['title'])
        #获取简介
        tt = get_movie_intro(uri,True,m['title'],m['rating']['value'])
        times.append(tt[0])
        intros.append(tt[1])
for i in range(1,17):
    with open(f'data/movie{i}.json','r',encoding='utf-8') as f:
        dic = json.load(f)
        handle_base_data(dic)
        print(directors)
        print(times)